// src/logger/logger.service.ts
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateLoggerDto } from './dto/create-logger.dto'
import { Logger } from './entities/logger.entity'
import { KeywordPageQuery } from 'types/global'

@Injectable()
export class LoggerService {
  constructor(
    @InjectRepository(Logger)
    private readonly loggerRepository: Repository<Logger>
  ) {}

  async log(createLoggerDto: CreateLoggerDto): Promise<Logger> {
    const logger = new Logger(createLoggerDto)
    return this.loggerRepository.save(logger)
  }

  async findAll(params: KeywordPageQuery) {
    const { keyword = '', pageNum = 1, pageSize = 10 } = params
    const skip = (pageNum - 1) * pageSize
    try {
      const queryBuilder = this.loggerRepository.createQueryBuilder('logger')

      // 级联查询 user 表并选择 username 字段
      // queryBuilder.leftJoinAndSelect(
      //   'logger.user',
      //   'user',
      //   'user.id = logger.userId'
      // )

      if (keyword) {
        queryBuilder.where(
          'logger.name LIKE :keyword OR logger.param LIKE :keyword',
          { keyword: `%${keyword}%` }
        )
      }

      // 按 createTime 字段降序排序
      queryBuilder.orderBy('logger.createTime', 'DESC')

      const [list, total] = await queryBuilder
        .skip(skip)
        .take(pageSize)
        .getManyAndCount()

      return {
        list,
        total,
        pageNum,
        pageSize
      }
    } catch (error) {
      console.log(error)
      throw error
    }
  }
}
